import {parseFormulaStr, dal2Rpn, STATUS, evalRpn} from '@/components/business-modules/report/base/formulaUtil.js'
import {getCallTimeLength, deepClone} from './m7Utils.js'
// 翻页导出任务数值存储
export const exportNum = {
  searchNum: 1000001,      // 初始查询值
  endExportNum: 100000, // 大于这个值走任务
  maxExportNum: 1000000 // 最多不能超出多少
}
// 自定义公式算法
export function mixData (data, formulas) {
  let rateArray = ['CallInAcceptRate', 'TransferAcceptRate', 'IntegratedCallInAcceptRate', 'AgentUtilization', 'approveSurveyRate', 'sessionCompleteRate', 'inviteSessionRate', 'responseIn40sRate', 'agentInviteRate', 'inviteRate', 'appraiseRate', 'appraiseRateOld', 'sessionRate', 'accessRate', 'queueGiveupRate', 'csr_rate']
  data.forEach(item => {
    formulas.forEach((formula, index) => {
      const map = formula.map // 公式值对应字段名 常量为 _const
      // const defaultValues = formula.defaultValues // 新建公式默认值
      let getValue = (token) => {
        if (token.state === STATUS.VALUE) {
          return Number(token.value)
        } else {
          let factor = token.subString

          if (map[factor] && map[factor] === '_const') {
            return Number(factor)
          }

          if (map[factor] && map[factor] !== '_const') {
            let key = map[factor] // 对应公式得表头字段名
            var result = parseFloat(item[key])
            // length > 40 是判断在线技能组质量对比报表自定义率得问题
            if (rateArray.includes(key) || (key.indexOf('_rate') > -1 && key.length > 40)) { // 判断字段名是否为率 率需转换为数字
              return isNaN(result) ? 0 : result / 100
            } else {
              return isNaN(result) ? 0 : result
            }
          }
          return 0
        }
      }
      try {
        let parseResult = parseFormulaStr(formula.formulaStr) // 解析公式表达式 生成数组包对象形式[{state: "FACTOR", subString: "c"}]
        let rpns = dal2Rpn(parseResult) // 中缀转后缀完成 生成数组包对象形式[{state: "FACTOR", subString: "c"}]
        let result = {}
        if (rpns.length === 1 && rpns[0].state === 'FACTOR') { // 判断公式是否为一个值
          result = {
            state: STATUS.VALUE,
            value: getValue(rpns[0])
          }
        } else {
          result = evalRpn(rpns, (fir, sec, cur) => {
            let v0 = getValue(fir)
            let v1 = getValue(sec)
            let value = NaN
            switch (cur.subString) {
              case '+':
                value = v0 + v1
                break
              case '-':
                value = v0 - v1
                break
              case '*':
                value = v0 * v1
                break
              case '/':
                if (v0 === 0) { // 判断分子是否为0 v0分子 v1分母
                  value = 0
                } else {
                  if (v1 === 0) {
                    value = 1
                  } else {
                    value = v0 / v1
                  }
                }
                break
              default:
                break
            }
            return {
              state: STATUS.VALUE,
              value: value
            }
          })
        }
        // item['_formulas_' + formula.name] = isNaN(result.value) ? result.value
        if (formula.type === 'seconds') { // 结果是否转化为s
          // item[formula.name] = formula.digits ? `${result.value.toFixed(formula.digits)}` + 's' : result.value + 's'
          item[formula.name] = isNaN(result.value) ? result.value : `${result.value.toFixed(formula.digits)}s`
        } else if (formula.type === 'minOrSec') { // 结果是否转化为时分秒 小于0 转化为负得时分秒
          item[formula.name] = isNaN(result.value) ? result.value : result.value < 0 ? '-' + getCallTimeLength(Math.abs(result.value)) : getCallTimeLength(result.value)
        } else if (formula.type === 'percentage') { // 结果是否转化为百分数
          item[formula.name] = isNaN(result.value) ? result.value : (result.value * 100).toFixed(formula.digits) + '%'
        } else {
          item[formula.name] = isNaN(result.value) ? result.value : result.value.toFixed(formula.digits)
        }
      } catch (error) {
        console.log(error, 'gggggggggggggggg')
        item[formula.name] = '计算失败'
      }
    })
  })
  return data
}
// 排序算法
export function cusSort (name) {
  return function (c, d) {
    if (typeof c[name] === 'number' || (name.includes('_formulas') && c[name].indexOf(':') === -1 && c[name].indexOf('%') === -1)) {
      return parseFloat(d[name]) - parseFloat(c[name])
    } else if (c[name].indexOf(':') > -1 && d[name].indexOf(':') > -1 && parseInt(c[name].split(':').join('')) && parseInt(d[name].split(':').join('')) && name !== 'ReportTime' && name !== 'reportTime') {
      return parseInt(d[name].split(':').join('')) - parseInt(c[name].split(':').join(''))
    } else {
      if (c[name].indexOf('%') > -1 || (d[name].indexOf('s') > -1 && c[name].indexOf('s') > -1)) {
        return parseFloat(d[name]) - parseFloat(c[name])
      } else {
        return d[name].localeCompare(c[name], 'zh')
      }
    }
  }
}
export function getCallLabelReportKeys (finishOption, finishKeys, str) {
  for (let i = 0; i < finishOption.length; i++) {
    let newStr = str
    if (newStr) {
      newStr += '-->' + finishOption[i].name
      finishKeys[finishOption[i]._id] = newStr
    } else {
      finishKeys[finishOption[i]._id] = finishOption[i].name
      newStr = finishOption[i].name
    }
    let options = deepClone(finishOption[i].child)
    if (options && options.length > 0) {
      getCallLabelReportKeys(options, finishKeys, newStr)
    }
  }
  return finishKeys
}
/*
  导出PDF
*/
export function exportReportPdf (data) {
  let newWin = window.open('', 'report_export_pdf_show_print', '')
  // 避免document.write()叠加输出
  newWin.document.close()
  let html = document.createElement('div')
  html.innerHTML = document.getElementById(data.id).innerHTML
  let percent = html.querySelectorAll('td.percent div.cell')
  let second = html.querySelectorAll('td.second div.cell')
  percent.forEach((item) => {
    item.innerHTML += '%'
  })
  second.forEach((item) => {
    item.innerHTML += 's'
  })
  let tableHTML = html.innerHTML
  newWin.document.write('<style type="text/css">*{margin:0;padding:0}table{border-collapse:collapse;width:100%!important;}td{ border:1px solid #999}th{ border:1px solid #999;}.export,.deploy{display: none}</style>')
  newWin.document.write('<h3>' + data.title + '</h3>')
  newWin.document.write(tableHTML)
  // newWin.document.location.reload()   // safari 用这个方法会被踢出
  newWin.print()
}
/*
  导出PDF（图是抓页面的，表格是自己重写的=》 大数据量虚拟滚动的时候拿不到全部dom）
*/
export function exportReportPdfNew (data) {
  let html = document.createElement('div')
  html.innerHTML = document.getElementById(data.id).innerHTML
  let theadStr = ''
  let tbodyStr = ''
  let tfootStr = '<tfoot><tr>'
  let str = '<table><thead>'
  if (data.tableData.length > 0) {
    data.tableData.forEach((tableItem, index) => {
      tbodyStr += '<tr>'
      data.headConfig.forEach(headItem => {
        if (index < 1) { // 表头只取一次
          theadStr += `<th>${headItem.displayname}</th>`
        }
        tbodyStr += `<td>${tableItem[headItem.name] !== undefined ? tableItem[headItem.name] : ''}</td>`
      })
    })
    if (data.totalData && data.totalData.length >= 0) { // 合计
      const obj = data.totalData[0]
      Object.keys(obj).forEach(key => {
        tfootStr += `<td>${obj[key]}</td>`
      })
    }
  } else { // 暂无数据
    data.headConfig.forEach(item => {
      theadStr += `<th>${item.displayname}</th>`
    })
    tbodyStr = `<td colspan="${data.headConfig.length}" style="text-align:center;">暂无数据</td>`
  }
  str += theadStr
  str += '</thead><tbody>'
  str += `${tbodyStr}</tbody>`
  str += `${tfootStr}</tr></tfoot></table>`
  html.innerHTML = html.innerHTML + str
  let tableHTML = html.innerHTML
  let newWin = window.open('', 'report_export_pdf_show_print', '')
  // 避免document.write()叠加输出
  newWin.document.close()
  newWin.document.write('<style type="text/css">*{margin:0;padding:0}table{border-collapse:collapse;width:100%!important;}td{ border:1px solid #999}th{ border:1px solid #999;}.export,.deploy{display: none}</style>')
  newWin.document.write('<h3>' + data.title + '</h3>')
  newWin.document.write(tableHTML)
  // newWin.document.location.reload()   // safari 用这个方法会被踢出
  newWin.print()
}
export function sortDataByKey (data, key, order) {
  data.sort(function (a, b) {
    if (!order) {
      if (parseInt(a[key]) > parseInt(b[key])) {
        return 1
      } else if (parseInt(a[key]) === parseInt(b[key])) {
        return 0
      } else {
        return -1
      }
    } else {
      if (order === 'string') {
        return a[key].localeCompare(b[key], 'zh')
      } else {
        return b[key] - a[key]
      }
    }
  })
  return data
}
/*
  导出报表表头的时间设置
*/
export function searchTime (query) {
  if (query.timeType === 'year') {
    return ' 年报（' + query.yearReport + '年' + ')'
  } else if (query.timeType === 'month') {
    return ' 月报（' + query.yearReport + '年' + query.monthReport + '月' + ')'
  } else if (query.timeType === 'day') {
    return ' 日报（' + query.yearReport + '年' + query.monthReport + '月' + query.dayReport + '日' + ')'
  } else {
    return ''
  }
}
/**
 * 格式化时间
 */
export function formatDateQuery (query) {
  let formatedQuery = {}
  for (let key in query) {
    if (typeof query[key] === 'number') {
      if (query[key] > 9) {
        formatedQuery[key] = '' + query[key]
      } else {
        formatedQuery[key] = '0' + query[key]
      }
    } else {
      formatedQuery[key] = query[key]
    }
  }
  return formatedQuery
}

/**
* 检验查询类型和时间格式
* 自定义类型规则：不可为空
* canBeNull：是否可以为空；isDay：是否到天
*/
export function checkTime (start, end, canBeNull, isDay) {
  let msg
  let startTime = start ? start.replace(/-/g, '').replace(/:/g, '').replace(/\s/g, '') : 0
  let endTime = end ? end.replace(/-/g, '').replace(/:/g, '').replace(/\s/g, '') : 0
  let temp = isDay ? 10000 : 100000000
  if (startTime && endTime) { // 起止时间均不为0
    if (startTime / temp > 1 && endTime / temp > 1) { // 时间是否完整
      if (startTime > endTime) { // 起止时间是否颠倒
        msg = 'report.queryTimeErr'
      } else {
        let endDay = endTime.slice(0, 8)
        let startDay = startTime.slice(0, 8)
        msg = endDay - startDay < 10001 ? true : 'report.queryTimeRangeErr'
      }
    } else {
      msg = 'report.queryTypeErr'
    }
  } else {
    if (canBeNull) { // 是否可以为空
      if ((startTime + endTime) / temp > 0 && (startTime + endTime) / temp < 1) { // 时间是否完整
        msg = 'report.queryTypeErr'
      } else {
        msg = true
      }
    } else {
      msg = 'report.queryType'
    }
  }
  return msg
}
/**
* 重置highcharts的默认颜色
*/
// export let colorConfig = {c1: '#7cb5ec', c2: '#f7a35c', c3: '#90ee7e', c4: '#7798BF', c5: '#aaeeee', c6: 'ff0066', c7: '#eeaaee', c8: '#55BF3B', c9: '#DF5353', c10: '#7798BF'}
export let colorConfigArr = ['#7cb5ec', '#f7a35c', '#90ee7e', '#7798BF', '#aaeeee', '#ff0066', '#eeaaee', '#55BF3B', '#DF5353', '#7798BF']
export let statusCustColorArr = {
  status0: '#9761ad',
  status1: '#ED5870',
  status2: '#F48C4D',
  status3: '#FBB100',
  status4: '#79B05D',
  status5: '#5F89BB',
  status6: '#66BDC7',
  status7: '#9761AD',
  status8: '#BBC9D6',
  status9: '#CECECE'
}
// 地域报表涉及到的省
export let reportAreaProvince = ['未知号段', '北京市', '天津市', '上海市', '重庆市', '澳门', '福建省', '广东省', '安徽省', '广西', '甘肃省', '贵州省', '河北省', '河南省', '湖北省', '湖南省', '海南省', '黑龙江省', '浙江省', '江苏省', '江西省', '吉林省', '辽宁省', '内蒙古', '宁夏', '青海省', '山东省', '山西省', '陕西省', '四川省', '台湾省', '新疆', '西藏', '香港', '云南省']
export function headOptionsToXlsxHeaders (headOptionsConfig) {
  return headOptionsConfig.filter(d => d.show).map(d => {
    var result = {
      name: d.displayname,
      prop: d.name,
      width: 9
    }

    if (d.timeType === 'percent') {
      result.style = {
        numberFormat: '0\\%'
      }
    }

    if (d.timeType === 'second') {
      result.style = {
        numberFormat: '0\\s'
      }
    }

    return result
  })
}
